package com.itheima.history.service.impl;

import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.history.service.HistorService;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;

@Service

public class HistoryServiceImpl implements HistorService {
    final static String preHistory = "history_search_";
    final static String nologin = "nologin_";
    final static String login = "login_";
    @Autowired
    private RedisTemplate redisTemplate;


    public Result findHistory(String phone) {
        if (!StringUtils.isEmpty(phone)) {
            Set members = redisTemplate.boundSetOps(login + phone).members();
            if (members == null) {
                return new Result(true, StatusCode.OK, "没有搜索记录");
            }
            return new Result(true, StatusCode.OK, "查询成功", members);
        }


        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return new Result(true, StatusCode.OK, "没有搜索记录");
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().startsWith(preHistory)) {
                Set members = redisTemplate.boundSetOps(cookie.getValue()).members();
                return new Result(true, StatusCode.OK, "查询成功", members);

            }
        }

        return new Result(true, StatusCode.OK, "没有搜索记录");
    }


}
